package pers.xhh.shopapi.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.xhh.shopapi.annotation.UserLoginToken;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.entity.to.user.MiManagerTo;
import pers.xhh.shopapi.entity.to.user.MiManagerUpdateTo;
import pers.xhh.shopapi.entity.vo.user.LoginVo;
import pers.xhh.shopapi.service.MiManagerService;

import javax.validation.Valid;

/**
 * http://api/v1/login
 * @author wei-xhh
 * @date 2020-11-22
 */
@CrossOrigin
@RestController
@RequestMapping("/api/v1")
public class MiManagerController {

    @Autowired
    MiManagerService miManagerService;

    @PostMapping("/login")
    public Mi managerLogin(@RequestBody LoginVo loginVo){
        String password = loginVo.getPassword();
        String username = loginVo.getUsername();
        return miManagerService.login(username, password);
    }

    @UserLoginToken
    @GetMapping("/users")
    public Mi getUsers(@RequestParam(value = "query", required = false) String query,
                       @RequestParam("pagenum") Integer pagenum,
                       @RequestParam("pagesize") Integer pagesize){
        return miManagerService.listUser(query, pagenum, pagesize);
    }

    @UserLoginToken
    @PostMapping("/users")
    public Mi insertUser(@Valid @RequestBody MiManagerTo miManagerTo){
        return miManagerService.saveMiManagerTo(miManagerTo);
    }

    @UserLoginToken
    @PutMapping("/users/{uId}/state/{type}")
    public Mi updateUserState(@PathVariable("uId") Integer uId,
                              @PathVariable("type") Boolean type){
        return miManagerService.updateUserState(uId, type);
    }

    @UserLoginToken
    @GetMapping("/users/{uId}")
    public Mi getUserById(@PathVariable("uId") Integer uId){
        return miManagerService.getUserById(uId);
    }

    @UserLoginToken
    @PutMapping("/users/{uId}")
    public Mi updateUserById(@PathVariable("uId") Integer uId,
                             @Valid @RequestBody MiManagerUpdateTo miManagerUpdateTo){
        return miManagerService.updateUserById(uId, miManagerUpdateTo);
    }

    @UserLoginToken
    @DeleteMapping("/users/{uId}")
    public Mi deleteUserById(@PathVariable("uId") Integer uId){
        return miManagerService.deleteUserById(uId);
    }

    @UserLoginToken
    @PutMapping("/users/{uId}/role/{rid}")
    public Mi updateUserRole(@PathVariable("uId") Integer uId,
                             @PathVariable("rid") Integer rid){
        return miManagerService.updateUserRole(uId, rid);
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }

}
